var express = require('express');
var router = express.Router();

var User = require("./../models/user"); 
require("./../util/util");

/**
 * 登录
 */
router.post('/login', function(req, res, next) {
  let params = {
    userName: req.body.userName,
    userPwd: req.body.userPwd
  }
  User.findOne(params, function(err, doc){
    if(err){
      res.json({
        status: "1",
        msg: err.message
      });
    }else{
      if(doc){
        res.cookie("userName", doc.userName, {
          path: "/",
          maxAge: 1000 * 60 * 60
        });
        res.json({
          status: "0",
          msg: "",
          result: {
            userName: doc.userName
          }
        });
      }else{
        //在数据库里查询不到用户
        res.json({
          status: "2",
          msg: "用户名或密码错误",
          result: "用户名或密码错误"
        })
      }
    }
  });
});

/**
 * 登出
 */
router.post("/logout", function(req, res, next){
  res.cookie("userName", "", {
    path: "/",
    maxAge: -1
  });
  res.json({
    status: "0",
    msg: "",
    result: ""
  });
});

/**
 * 检查用户是否登录
 */
router.get("/checkLogin", function(req, res, next){
  if(req.cookies.userName){
    res.json({
      status: "0",
      msg: "已经登录",
      result: {
        userName: req.cookies.userName || ""
      }
    });
  }else{
    res.json({
      status: "1",
      msg: "未登录",
      result: ""
    });
  }
});

/**
 * 获取购物车数据列表
 */
router.get("/cartList", function(req, res, next){
  let userName = req.cookies.userName;
  User.findOne({userName:userName}, function(err, userList){
    if(err){
      res.json({
        status: "1",
        msg: err.message,
        result: ""
      });
    }else{
      if(userList){
        res.json({
          status: "0",
          msg: "",
          result: userList.cartList
        });
      }
    }
  });
});

/**
 * 根据用户名，商品id删除购物车内某件商品
 */
router.post("/cartDel", function(req, res, next){
  let userName = req.cookies.userName, productId = req.body.productId;
  User.update({userName:userName}, {$pull: {"cartList": {"productId": productId}}}, function(err, doc){
    if(err){
      res.json({
        status: "1",
        msg: err.message,
        result: ""
      });
    }else{
      res.json({
        status: "0",
        msg: "success",
        result: "delete product success"
      });
    }
  });
});

/**
 * 编辑购物车
 */
router.post("/cartEdit", function(req, res, next){
  let userName = req.cookies.userName, 
      productId = req.body.productId, 
      productNum = req.body.productNum,
      checked = req.body.checked;
  User.update({"userName": userName, "cartList.productId": productId}, {
    "cartList.$.productNum":productNum,
    "cartList.$.checked": checked
  }, function(err, doc){
    if(err){
      res.json({
        status: "1",
        msg: err.message,
        result: ""
      });8
    }else{
      res.json({
        status: "0",
        msg: "update cart success",
        result: ""
      });
    }
  });
});

/**
 * 购物车全选/反选
 */
router.post("/cartChecked", function(req, res, next){
  let userName = req.cookies.userName, checked=req.body.checkAllFlag?"1":"0";
  User.findOne({"userName": userName}, function(err, user){
    if(err){
      res.json({
        status: "1",
        msg: err.message,
        result: ""
      });
    }else{
      if(user){
        user.cartList.forEach((item)=>{
          item.checked = checked;
        });
        user.save(function(err, doc){
          if(err){
            res.json({
              status: "1",
              msg: err.message,
              result: ""
            });
          }else{
            res.json({
              status: "0",
              msg: "success",
              result: ""
            });
          }
        });
      }
    }
  });
});

/**
 * 查询用户地址
 */
router.get("/addressList", function(req, res, next){
  let userName = req.cookies.userName;
  User.findOne({"userName":userName}, function(err, user){
    if(err){
      res.json({
        status: "1",
        msg: err.msg,
        result: ""
      });
    }else{
      if(user){
        res.json({
          status: "0",
          msg: "get addressList success",
          result: user.addressList
        });
      }
    }
  });
});

/**
 * 设置默认地址
 */
router.post("/setDefaultAddress", function(req, res, next){
  let userName = req.cookies.userName, addressId = req.body.addressId;
  User.findOne({"userName": userName}, function(err, user){
    if(err){
      res.json({
        status: "1",
        msg: err.messge,
        result: ""
      });
    }else{
      if(user){
        let addressList = user.addressList;
        addressList.forEach((item)=>{
          if(item.addressId == addressId){
            item.isDefault = true;
          }else{
            item.isDefault = false;
          }
        });
        user.save(function(err, doc){
          if(err){
            res.json({
              status: "1001",
              msg: err.message,
              result: ""
            });
          }else{
            res.json({
              status: "0",
              msg: "set default address success",
              result: ""
            });
          }
        });
      }
    }
  });
});

/**
 * 删除地址
 */
router.post("/delAddress", function(req, res, next){
  let userName = req.cookies.userName, addressId = req.body.addressId;
  User.update({"userName":userName}, {$pull: {"addressList": {"addressId": addressId}}}, function(err, doc){
    if(err){
      res.json({
        status: "1",
        msg: err.message,
        result: ""
      });
    }else{
      if(doc){
        res.json({
          status: "0",
          msg: "delete address success",
          result: ""
        });
      }
    }
  });
});

/**
 * 生成订单
 */
router.post("/payment", function(req, res, next){
  let userName = req.cookies.userName, orderTotal = req.body.orderTotal, addressId = req.body.addressId;
  User.findOne({"userName": userName}, function(err, doc){
    if(err){
      res.json({
        status: "1",
        msg: err.message,
        result: ""
      });
    }else{
      let address = "", goodsList = [];
      //获取地址
      doc.addressList.forEach((item)=>{
        if(addressId == item.addressId){
          address = item;
        }
      });
      //获取用户购物车的购买商品
      doc.cartList.filter((item)=>{
        if(item.check == "1"){
          goodsList.push(item);
        }
      });

      let random1 = Math.floor(Math.random() * 10);
      let random2 = Math.floor(Math.random() * 10);
      let sysdate = new Date().Format("yyyyMMddhhmmss");
      let createDate = new Date().Format("yyyy-MM-dd hh:mm:ss");
      let orderId = "7506" + random1 + sysdate + random2;

      let order = {
        "orderId": orderId,
        "orderTotal": orderTotal,
        "addressInfo": address,
        "goodsList": goodsList,
        "orderStatus": "1",
        "createDate": createDate
      }

      doc.orderList.push(order);

      doc.save(function(err1, doc1){
        if(err1){
          res.json({
            status: "1",
            msg: err.message,
            result: ""
          });
        }else{
          if(doc1){
            res.json({
              status: "0",
              msg: "",
              result: {
                "orderId": order.orderId,
                "orderTotal": orderTotal
              }
            });
          }
        }
      });
    }
  });
});

/**
 * 根据订单id查询订单信息
 */
router.get("/orderDetail", function(req, res, next){
  let userName = req.cookies.userName, orderId = req.param("orderId");
  User.findOne({"userName": userName}, function(err, userInfo){
    if(err){
      res.json({
        status: "1",
        msg: err.message,
        result: ""
      });
    }else{
      if(userInfo){
        let orderList = userInfo.orderList;
        if(orderList.length > 0){
          let orderTotal = 0;
          orderList.forEach((item)=>{
            if(item.orderId == orderId){
              orderTotal = item.orderTotal; 
            }
          });
          res.json({
            status: "0",
            msg: "",
            result: {
              orderId: orderId,
              orderTotal: orderTotal
            }
          });
        }else{
          res.json({
            status: "10012",
            msg: "order is null",
            result: ""
          });
        }
      }
    }
  });
});

/**
 * 获取购物车内的商品数量
 */
router.get("/getCartCount", function(req, res, next){
  if(req.cookies && req.cookies.userName){
    let userName = req.cookies.userName;
    User.findOne({"userName": userName}, function(err, user){
      if(err){
        res.json({
          status: "1",
          msg: err.message,
          result: ""
        });
      }else{
        if(user){
          let cartList = user.cartList;
          let cartCount = 0;
          cartList.forEach((item)=>{
            cartCount += parseInt(item.productNum);
          });
          res.json({
            status: "0",
            msg: "",
            result: cartCount
          });
        }
      }
    });
  }
});

module.exports = router;
